package org.summerframework.component.upload;

import org.summerframework.component.upload.exception.UploadFileException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * @author 石超
 * @version v1.0.0
 */
@Slf4j
public class DefaultUploadServerServiceImpl extends AbstractUploadServerService implements FileUploadServerService {
    private String filePath;

    public DefaultUploadServerServiceImpl(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public String uploadFile(InputStream is, String fileName) {
        String path = getPath(fileName);
        String savePath = getPath(filePath, path);
        File file1 = new File(savePath);
        if (!file1.getParentFile().exists() && !file1.getParentFile().mkdirs()) {
            throw new UploadFileException(UploadResultCode.ERROR_UPLOAD_FAILURE);
        }

        File oigFile = new File(savePath);

        try (FileOutputStream fos = new FileOutputStream(oigFile)) {
            IOUtils.copy(is, fos);
        } catch (IOException e) {
            throw new UploadFileException(UploadResultCode.ERROR_UPLOAD_FAILURE);
        }

        return path;
    }

    @Override
    public byte[] getFileBytes(String path) {
        File oigFile = new File(filePath + path);

        try {
            return FileUtils.readFileToByteArray(oigFile);
        } catch (IOException e) {
            e.printStackTrace();
            return EMPTY_BYTES;
        }
    }

    @Override
    public InputStream getInputStream(String path) throws IOException {
        return new FileInputStream(filePath + path);
    }

    @Override
    public void deleteFile(String path) {
        try {
            FileUtils.deleteQuietly(new File(filePath + path));
        } catch (Exception e) {
            log.warn("删除文件异常", e);
        }
    }
}
